<template>
  <select
    class="text-gray-800 leading-normal shadow-none px-0 bg-transparent border-none outline-none focus:(outline-none ring-0)"
    :name="name"
    :value="modelValue"
    @change="onChange"
  >
    <template v-for="option of items">
      <slot :option="option">
        <option :key="option.value" :value="option.value">
          {{ option.label }}
        </option>
      </slot>
    </template>
  </select>
</template>
<script lang="ts" setup>
import { computed } from "vue";

const props = defineProps({
  options: {
    type: [Array, Object],
    required: true,
  },
  defaultValue: String,
  defaultLabel: String,
  valueProp: {
    type: String,
    default: "value",
  },
  labelProp: {
    type: String,
    default: "label",
  },
  modelValue: String,
  name: {
    type: String,
    required: true,
  },
});

const emit = defineEmits(["update:modelValue"]);
const onChange = (e: Event) => {
  emit("update:modelValue", (e.target as HTMLInputElement).value);
};

const items = computed(() => {
  const options: Array<{ label: string; value: any }> = [];
  if (props.defaultValue)
    options.push({
      label: props.defaultLabel ?? props.defaultValue,
      value: props.defaultValue,
    });
  const data = Array.isArray(props.options)
    ? props.options
    : Object.entries(props.options);
  for (const i of data) {
    if (Array.isArray(i)) {
      const [value, label] = i;
      options.push({ value, label });
    } else {
      const { [props.valueProp]: value, [props.labelProp]: label } = i as any;
      options.push({ value, label });
    }
  }
  return options;
});
</script>
